package face.pay.cpn.mchinfo.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.github.wxpay.sdk.WXPayUtil;
import face.pay.cpn.AbstractApiService;
import face.pay.cpn.mchinfo.service.IGetMchInfoService;
import face.pay.cpn.utils.request.RequestParam;
import face.pay.cpn.utils.response.ErrorCode;
import face.pay.cpn.utils.response.ResponseMessage;
import face.pay.dao.*;
import face.pay.entity.*;
import face.pay.util.MathUtil;
import face.pay.vo.VoCpnCardUseTime;
import face.pay.vo.VoMchBaseInfo;
import face.pay.vo.VoMchInfo;
import face.pay.vo.VoStoreInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Service
public class GetMchInfoServiceimpl extends AbstractApiService implements IGetMchInfoService {


    @Autowired
    private CpnMchInfoDao cpnMchInfoDao;

    @Autowired
    private CpnMchServiceInfoDao cpnMchServiceInfoDao;

    @Autowired
    private StoreInfoDao storeInfoDao;

    @Autowired
    private CpnMchWorkTimeDao cpnMchWorkTimeDao;


    @Autowired
    private CpnMarketMchSourcesDao cpnMarketMchSourcesDao;

    @Autowired
    private CpnMarketSourcesConfigDao cpnMarketSourcesConfigDao;

    /**
     * 获取商家信息
     *
     * @param jsonData
     * @return
     */
    @Override
    public ResponseMessage getMchInfo(String jsonData) {
        return doApi(jsonData);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseMessage doService(CpnMarketInfo cpnMarketInfo, RequestParam requestParam) throws Exception {
        List<Integer> mchList = null;
        try {
            mchList = JSONArray.parseArray(requestParam.getData().get("mchList")).toJavaList(Integer.class);
        } catch (Exception e) {
            log.warn("参数有误market_code:{}", cpnMarketInfo.getMarket_code());
            return ResponseMessage.createParamFail();
        }

        if (mchList.size() == 0) {
            return ResponseMessage.createFail(ErrorCode.PARAM_FAIL_CODE, "每次至少查1条数据");
        }

        if (mchList.size() > 50) {
            return ResponseMessage.createFail(ErrorCode.PARAM_FAIL_CODE, "每次最多查50条数据");
        }

        CpnMarketSourcesConfig sourcesConfigRecord = new CpnMarketSourcesConfig();
        sourcesConfigRecord.setMarket_id(cpnMarketInfo.getId());
        CpnMarketSourcesConfig cpnMarketSourcesConfig = this.cpnMarketSourcesConfigDao.queryCpnMarketSourcesConfig(sourcesConfigRecord);

        log.info("开始查找商家信息market_id:{}", cpnMarketInfo.getId());

        List<VoMchBaseInfo> voMchBaseInfoList = this.cpnMchInfoDao.queryVoMchBaseInfo(mchList);
        List<VoStoreInfo> voStoreInfoList = this.storeInfoDao.queryVoStoreInfo(mchList);
        List<VoCpnCardUseTime> voCpnCardUseTimeList = this.cpnMchWorkTimeDao.queryVoCpnCardUseTime(mchList);

        ArrayList<VoMchInfo> dataList = new ArrayList<>();

        ArrayList<CpnMarketMchSources> marketMchSourcesInsertList = new ArrayList<>();
        ArrayList<CpnMarketMchSources> marketMchSourcesUpdateList = new ArrayList<>();

        for (Integer mchId : mchList) {

            //获取商家服务配置
            CpnMchServiceInfo cpnMchServiceInfoRecord = new CpnMchServiceInfo();
            CpnMchInfo cpnMchInfoRecord = new CpnMchInfo();
            cpnMchInfoRecord.setMerchant_id(mchId);
            CpnMchInfo cpnMchInfo = this.cpnMchInfoDao.queryCpnMchInfo(cpnMchInfoRecord);
            if (cpnMchInfo == null) {
                continue;
            }
            cpnMchServiceInfoRecord.setUserId(cpnMchInfo.getUserId());
            CpnMchServiceInfo cpnMchServiceInfo = this.cpnMchServiceInfoDao.queryCpnMchServiceInfo(cpnMchServiceInfoRecord);

            //计算费率
            Double marketFeel = 0d;
            Double subFeel = MathUtil.sub(MathUtil.sub(cpnMchServiceInfo.getService_fee(), cpnMarketSourcesConfig.getCpn_fee()), cpnMarketSourcesConfig.getOem_fee());
            if (cpnMarketSourcesConfig.getMax_mch_fee() == null || Double.valueOf(0).equals(cpnMarketSourcesConfig.getMax_mch_fee())) {
                //费率无限制
                marketFeel = subFeel;
            } else {

                marketFeel = subFeel <= cpnMarketSourcesConfig.getMax_mch_fee() ? subFeel : cpnMarketSourcesConfig.getMax_mch_fee();
            }


            //准备data参数
            VoMchInfo mchInfoData = new VoMchInfo();
            mchInfoData.setMerchant_id(mchId);

            VoMchBaseInfo voMchBaseInfo = voMchBaseInfoList.stream().filter(o -> mchId.equals(o.getMerchant_id())).findAny().orElse(null);
            voMchBaseInfo.setService_fee(marketFeel);
            mchInfoData.setBaseInfo(voMchBaseInfo);

            List<VoStoreInfo> storeList = voStoreInfoList.stream().filter(o -> mchId.equals(o.getMerchant_id())).collect(Collectors.toList());
            mchInfoData.setStoreList(storeList);

            List<VoCpnCardUseTime> cpnUseTimes = voCpnCardUseTimeList.stream().filter(o -> mchId.equals(o.getMerchant_id())).collect(Collectors.toList());
            mchInfoData.setCpnUseTimes(cpnUseTimes);
            dataList.add(mchInfoData);

            //比较费用 添加到插入或更新的集合中
            CpnMarketMchSources record = new CpnMarketMchSources();
            record.setMarket_id(cpnMarketInfo.getId());
            record.setMerchant_id(mchId);
            CpnMarketMchSources sources = this.cpnMarketMchSourcesDao.queryCpnMarketMchSources(record);


            if (sources == null) {
                //新增的
                CpnMarketMchSources updateSoures = new CpnMarketMchSources();
                updateSoures.setMerchant_id(voMchBaseInfo.getMerchant_id());
                updateSoures.setMarket_id(cpnMarketInfo.getId());
                updateSoures.setOemId(voMchBaseInfo.getChannelId());
                updateSoures.setMch_user_id(cpnMchInfo.getUserId());
                updateSoures.setMarket_feel(marketFeel);
                marketMchSourcesInsertList.add(updateSoures);
            } else {
                //更新的
                if (!sources.getMarket_feel().equals(marketFeel)) {
                    //费率不一样更新
                    sources.setMarket_feel(marketFeel);
                    marketMchSourcesUpdateList.add(sources);
                }
            }
        }

        //批量更新和插入
        if (marketMchSourcesInsertList.size() > 0) {
            this.cpnMarketMchSourcesDao.insertlist(marketMchSourcesInsertList);
            log.info("新增平台结算费率market_id:{} 共:{}条", cpnMarketInfo.getId(), marketMchSourcesInsertList.size());
        }
        if (marketMchSourcesUpdateList.size() > 0) {
            this.cpnMarketMchSourcesDao.updataList(marketMchSourcesUpdateList);
            log.info("更新平台结算费率market_id:{} 共:{}条", cpnMarketInfo.getId(), marketMchSourcesUpdateList.size());
        }
        log.info("查找商家信息结束market_id:{} 共:{}条", cpnMarketInfo.getId(), dataList.size());
        return ResponseMessage.createSuccess(null, dataList);
    }


}

